import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";

interface ILoginAction {
  login: boolean;
}

function waitRandom(): Promise<void> {
  return new Promise(resolve => {
    setTimeout(() => resolve(), (Math.random() + 1) * 1000 * 5)
  })
}

export const asyncLogin = createAsyncThunk(
  'login/get',
  async () => {
    await waitRandom();
    return {
      login: true
    }
  }
)

export const loginSlice = createSlice({
  name: "login",
  initialState: {login: false},
  reducers: {},
  /*extraReducers: {
    [asyncLogin.pending.type]: (state) => state,
    [asyncLogin.fulfilled.type]: (state, action: PayloadAction<ILoginAction>) => action.payload
  }*/
  extraReducers: (builder => {
    builder.addCase(asyncLogin.fulfilled,(state, action:PayloadAction<ILoginAction>) => {
      return action.payload
    });
    builder.addCase(asyncLogin.pending,state => {
      return state
    })
  })
})
